define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'feditionreport/index' + location.search,
                    add_url: 'feditionreport/add',
                    edit_url: 'feditionreport/edit',
                    del_url: 'feditionreport/del',
                    multi_url: 'feditionreport/multi',
                    import_url: 'feditionreport/import',
                    table: 'fedition_report',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'timedate', title: __('Timedate'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, datetimeFormat:"YYYY-MM-DD"},
                        {field: 'admin_id', title: __('操作人'),visible: false,addClass: "selectpage", extend: "data-source='auth/admin/index' data-field='nickname'"},
                        {field: 'admin_name', title: __('操作人'), operate: false},
                        {field: 'number', title: __('Number'),visible: false,addClass: "selectpage", extend: "data-source='feditionaccount/index' data-field='number'"},
                        {field: 'number_name', title: __('Number'), operate: false,formatter: function(value){return value.toString().substr(0, 10)}},

                        {field: 'amount', title: __('Amount'), operate:'BETWEEN'},
                        {field: 'advertising', title: __('Advertising'), operate:'BETWEEN'},
                        {field: 'sales', title: __('Sales'), operate:'BETWEEN'},
                        {field: 'output_ratio', title: __('Output_ratio'), operate: 'LIKE'},
                        {field: 'through_rate', title: __('Through_rate'), operate: 'LIKE'},
                        {field: 'conversion_rate', title: __('Conversion_rate'), operate: 'LIKE'},
                        {field: 'cpc', title: __('Cpc'), operate: 'LIKE'},
                        {field: 'single_transfer', title: __('Single_transfer'), operate: 'LIKE'},
                        {field: 'single_quantity', title: __('Single_quantity'), operate: 'LIKE'},
                        {field: 'passenger_volume', title: __('Passenger_volume'), operate: 'LIKE'},
                        {field: 'delivery_area', title: __('Delivery_area'), operate: 'LIKE'},
                        // {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        // {
                        //     field: 'buttons',
                        //     width: "120px",
                        //     title: __('充值'),
                        //     table: table,
                        //     events: Table.api.events.operate,
                        //     operate: false,
                        //     buttons: [
                            // {
                            //     name: 'detail',
                            //     text: __('充值'),
                            //     title: __('充值'),
                            //     classname: 'btn btn-sm btn-primary btn-dialog',
                            //     icon: 'fa fa-ravelry',
                            //     url: 'feditionrecharge/add'
                            // },
                            // {
                            //     name: 'detail',
                            //     text: __('查看充值记录'),
                            //     title: __('查看充值记录'),
                            //     classname: 'btn btn-sm btn-warning btn-dialog',
                            //     icon: 'fa fa-list',
                            //     url: 'feditionrecharge/index/?account_id={ids}',
                            //     // visible:function (row) {
                            //     //     if(row.dns_id == 0){
                            //     //         return true;
                            //     //     }else{
                            //     //         return false;
                            //     //     }
                            //     // }
                            // },
                            // {
                            //     name: 'detail',
                            //     text: __('账户余额'),
                            //     title: __('账户余额'),
                            //     classname: 'btn btn-sm btn-info btn-dialog',
                            //     icon: 'fa fa-leaf',
                            //     url: 'feditionbalance/index/?account_id={ids}'
                            // }
                        //     ],
                        //     formatter: Table.api.formatter.buttons
                        // },
                        {
                            field: 'buttons',
                            width: "120px",
                            title: __('操作记录'),
                            table: table,
                            events: Table.api.events.operate,
                            operate: false,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: __('操作记录'),
                                    title: __('操作记录'),
                                    classname: 'btn btn-sm btn-success btn-dialog',
                                    icon: 'fa fa-magic',
                                    url: 'feditionlog/index/?type=5'
                                }
                            ],
                            formatter: Table.api.formatter.buttons
                        },
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                //这里可以获取从服务端获取的JSON数据
                console.log('zamount',data.Statistics.zamount);
                $("#zamount").text(data.Statistics.zamount);
                $("#zadvertising").text(data.Statistics.zadvertising);
                $("#zsales").text(data.Statistics.zsales);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $(document).on("fa.event.appendfieldlist", "#add-form .btn-append", function (e, obj) {
                Form.events.selectpage(obj);
                Form.events.datetimepicker(obj);
            });
            //销售额/广告花费 = 投入产出比
            $('#c-advertising').bind('input propertychange', function() {
                add_output_ratio();
                add_single_transfer();
            });
            $('#c-sales').bind('input propertychange', function() {
                add_output_ratio();
                add_passenger_volume();
            });
            function add_output_ratio(){
                var advertising = $('#c-advertising').val();
                var sales = $('#c-sales').val();
                advertising = Number(advertising);
                sales = Number(sales);
                if(advertising > 0 && sales > 0){
                    var output_ratio = (sales/advertising);
                    output_ratio = Math.floor(output_ratio * 100) / 100;
                    $('#c-output_ratio').val(output_ratio);
                }else{
                    $('#c-output_ratio').val('');
                }
            }
            //单转成本=广告花费/单量
            $('#c-single_quantity').bind('input propertychange', function() {
                add_single_transfer();
                add_passenger_volume();
            });
            function add_single_transfer(){
                var advertising = $('#c-advertising').val();
                var single_quantity = $('#c-single_quantity').val();
                advertising = Number(advertising);
                single_quantity = Number(single_quantity);
                if(advertising > 0 && single_quantity > 0){
                    var single_transfer = (advertising/single_quantity);
                    single_transfer = Math.floor(single_transfer * 100) / 100;
                    $('#c-single_transfer').val(single_transfer);
                }else{
                    $('#c-single_transfer').val('');
                }
            }
            //客单价=销售额/单量
            function add_passenger_volume(){
                var single_quantity = $('#c-single_quantity').val();
                var sales = $('#c-sales').val();
                single_quantity = Number(single_quantity);
                sales = Number(sales);
                if(single_quantity > 0 && sales > 0){
                    var passenger_volume = (sales/single_quantity);
                    passenger_volume = Math.floor(passenger_volume * 100) / 100;
                    $('#c-passenger_volume').val(passenger_volume);
                }else{
                    $('#c-passenger_volume').val('');
                }
            }

            Controller.api.bindevent();
            $("#c-number").data("formatItem",function (item) {
                return "账户编号:"+item.number+",账户描述:"+item.description;
            });

            //投放时间改变，获取销售额
            $('#c-timedate').on('dp.change', function(e){
                update_sales();
            });
            $('#c-number').on('change', function(e){
                update_sales();
            });
            function update_sales() {
                var number = $('#c-number').val();
                var timedate = $('#c-timedate').val();
                Fast.api.ajax({
                    url: "feditionreport/update_sales",
                    async: false,
                    data: {timedate: timedate,number: number}
                }, function (data) {
                    $("#c-sales").val(data.sales);
                    return false;
                });
            }

        },
        edit: function () {
            $(document).on("fa.event.appendfieldlist", "#edit-form .btn-append", function (e, obj) {
                Form.events.selectpage(obj);
                Form.events.datetimepicker(obj);
            });
            add_output_ratio();
            add_single_transfer();
            add_passenger_volume();
            //销售额/广告花费 = 投入产出比
            $('#c-advertising').bind('input propertychange', function() {
                add_output_ratio();
                add_single_transfer();
            });
            $('#c-sales').bind('input propertychange', function() {
                add_output_ratio();
                add_passenger_volume();
            });
            function add_output_ratio(){
                var advertising = $('#c-advertising').val();
                var sales = $('#c-sales').val();
                advertising = Number(advertising);
                sales = Number(sales);
                if(advertising > 0 && sales > 0){
                    var output_ratio = (sales/advertising);
                    output_ratio = Math.floor(output_ratio * 100) / 100;
                    $('#c-output_ratio').val(output_ratio);
                }else{
                    $('#c-output_ratio').val('');
                }
            }
            //单转成本=广告花费/单量
            $('#c-single_quantity').bind('input propertychange', function() {
                add_single_transfer();
                add_passenger_volume();
            });
            function add_single_transfer(){
                var advertising = $('#c-advertising').val();
                var single_quantity = $('#c-single_quantity').val();
                advertising = Number(advertising);
                single_quantity = Number(single_quantity);
                if(advertising > 0 && single_quantity > 0){
                    var single_transfer = (advertising/single_quantity);
                    single_transfer = Math.floor(single_transfer * 100) / 100;
                    $('#c-single_transfer').val(single_transfer);
                }else{
                    $('#c-single_transfer').val('');
                }
            }
            //客单价=销售额/单量
            function add_passenger_volume(){
                var single_quantity = $('#c-single_quantity').val();
                var sales = $('#c-sales').val();
                single_quantity = Number(single_quantity);
                sales = Number(sales);
                if(single_quantity > 0 && sales > 0){
                    var passenger_volume = (sales/single_quantity);
                    passenger_volume = Math.floor(passenger_volume * 100) / 100;
                    $('#c-passenger_volume').val(passenger_volume);
                }else{
                    $('#c-passenger_volume').val('');
                }
            }

            Controller.api.bindevent();
            $("#c-number").data("formatItem",function (item) {
                return "账户编号:"+item.number+",账户描述:"+item.description;
            });

            //投放时间改变，获取销售额
            // $('#c-timedate').on('dp.change', function(e){
            //     update_sales();
            // });
            $('#c-number').on('change', function(e){
                update_sales();
            });
            function update_sales() {
                var oldsales = $("#c-sales").val();
                var number = $('#c-number').val();
                var timedate = $('#c-timedate').val();
                Fast.api.ajax({
                    url: "feditionreport/update_sales",
                    async: false,
                    data: {timedate: timedate,number: number}
                }, function (data) {
                    if(oldsales !== data.sales){
                        alert('销售额发生改变,shopify接口获取的销售额为'+data.sales);
                        $("#c-sales").val(data.sales);
                    }
                    return false;
                });
            }
        },
        api: {
            bindevent: function () {
                require(['selectpage'], function (SelectPage) {
                    var _displayResults = $.fn.selectPage.Constructor.prototype.displayResults;
                    $.fn.selectPage.Constructor.prototype.displayResults = function (self, json, is_query) {
                        _displayResults.call(this, self, json, is_query);
                        if (self.elem.hidden.is("#c-number")) {
                            $(self.elem.results[0]).append("<p class='text-center' style='margin:5px;'><a class='btn btn-xs btn-info btn-dialog' title='新增账户编号' data-window='top' href='feditionaccount/add'>新增账户编号</a></p><p style='margin:5px;'>（新增账户编号后需要取消下拉框，重新选择）</p>");
                        }
                        if (self.elem.hidden.is("#c-type")) {
                            $(self.elem.results[0]).append("<p class='text-center' style='margin:5px;'><a class='btn btn-xs btn-info btn-dialog' title='新增金额类型' data-window='top' href='feditionmoneytype/add'>新增金额类型</a></p><p style='margin:5px;'>（新增金额类型后需要取消下拉框，重新选择）</p>");
                        }
                    };
                });
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});